package server;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


public class ServerSender extends Thread {
	
	// 用一次的变量
	private boolean getWriter = false; // 申请BufferedWriter后变为true
	private boolean getOutputStream = false; // 申请outputStream后变为true
	
	// 获取流的容器
	private BufferedWriter writer = null;
	private FileOutputStream outputStream = null;

	// 存储变量
	private Socket sock;
	private boolean isFile;
	private boolean haveMessage;
	private String message;
	byte[] file;


	// 构造函数：sock
	public ServerSender(Socket so) {
		isFile = false;
		this.haveMessage = false;
		this.message = "";
		this.sock = so;
		file = new byte[1024];
	}


	// 线程开始开始循环 调用sendMessage()发送消息
	public synchronized void run() {
		try (OutputStream output = sock.getOutputStream()) {

			System.out.println("发送就绪");
			while (true) {

				// 传输信息
				if (!isFile) {

					// 没有初始化的时候才获取reader
					if(!getWriter) { 
						writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
						getWriter = true;
					}
					// 模拟发消息需要0.1秒
					Thread.sleep(100);
					// 有消息的时候发送
					if (haveMessage) {
						System.out.println("消息：" + message + "向" + sock.getInetAddress().toString() + "发送");
						writer.write(this.message); // 地址信息一起发
						writer.flush();
						System.out.println("消息发送成功");
						haveMessage = !haveMessage;
					}
				}
				
				// 传输文件
				else if(isFile) {
					if(!getOutputStream) {
						outputStream = (FileOutputStream) output;
						getOutputStream = true;
					}
					outputStream.write(file);
					
					isFile = !isFile;
				}
				

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	
	// 供外部使用的方法
	
	// 发消息方法
	public void sendMessage(String message) {
		haveMessage = true;
		this.message = message;
	}

	// 发文件方法
	public void sendFile(String address, byte[] p) throws InterruptedException {
		sendMessage("d"+address); // 先传输指令和地址
		Thread.sleep(100);
		// 设置直接传输文件
		isFile = true;
		file = p;
	}

	// 返回sock
	public Socket getSock() {
		return this.sock;
	}


}
